﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DD35.WebMVP.Presenters;
using AMS.Core.Services;
using AMS.DD35.WebMVP.Models;
using AMS.DD35.WcfConnector;
using AMS.DD35.WebMVP.State;

namespace AMS.DD35.WebMVP
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        //IPageMasterPresenter _presenter;
        AMS.DD35.WebMVP.State.IStateManager _state;
        ILoginModel _model;

        protected void Page_Load(object sender, EventArgs e)
        {
            ILoginService login = new LoginProxy();
            _state = new StateManager();
            _model = new LoginModel(login, _state);
            //_presenter = new PageMasterPresenter(this, _model, _state);

            _model.LogoutSucceeded += new EventHandler(HandleLogoutSucceeded);

            SetLoginStatus();
        }

        private void SetLoginStatus()
        {
            bool loggedIn = _state.SessionVariable != null;

            LoginLink.Visible = !loggedIn;
            WelcomeLabel.Visible = loggedIn;
            WelcomeLabel.Text = String.Format("Welcome {0}!", _state.UserName);
            LogoutLink.Visible = loggedIn;
        }

        protected void HandleLoginLink_Click(object sender, EventArgs args)
        {
            Response.Redirect("~/Views/LoginView.aspx", false);
        }

        protected void HandleLogoutLink_Click(object sender, EventArgs args)
        {
            _model.Logout();
        }

        private void HandleLogoutSucceeded(object sender, EventArgs args)
        {
            Response.Redirect("~/Views/LoginView.aspx");
        }
    }
}
